<script setup>
import { SaveFilled, RollbackOutlined } from '@ant-design/icons-vue';
import CodeEditor from '@/components/CodeEditor/CodeEditor.vue';
import { compileCode } from '@/apis/code.js';
import { saveAs } from 'file-saver';

const router = useRouter();
const $editor = ref();
const $iframe = ref();
const pageRoute = ref([
    { path: '/', breadcrumbName: '主页' },
    { path: '/code-online', breadcrumbName: '在线编程' },
]);

const iframeSrc = computed(() => {
    return `${import.meta.env.VITE_BASE_URL}/code/html`;
});

const runCode = async () => {
    const code = $editor.value.getCode();
    await compileCode(code);
    $iframe.value.src = iframeSrc.value;
};

const downloadPage = () => {
    const file = new File([$editor.value.getCode()], `${Date.now()}.html`, { type: 'text/plain;charset=utf-8' });
    saveAs(file);
};
</script>

<template>
    <section class="code-online-box">
        <section class="main">
            <section class="code-box">
                <CodeEditor ref="$editor" />
            </section>
            <section class="view-box">
                <div class="func-box">
                    <a-button type="primary" style="margin-right: 10px" @click="runCode">
                        <template #icon><SaveFilled /></template>
                    </a-button>
                    <a-button type="primary" style="margin-right: 10px" @click="downloadPage">下载页面</a-button>
                    <!-- <a-button danger type="default" style="margin-right: 10px">一键部署</a-button> -->
                    <a-button type="primary" ghost style="margin-right: 10px" @click="router.push({ name: 'Home' })">
                        <template #icon><RollbackOutlined /></template>
                        返回
                    </a-button>
                </div>
                <div class="combine-box">
                    <iframe ref="$iframe" width="100%" height="100%" style="border: none" :src="iframeSrc"></iframe>
                </div>
            </section>
        </section>
    </section>
</template>

<style scoped lang="scss">
.header {
    padding: 10px 30px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.code-online-box {
    height: 100%;
    display: flex;
    flex-direction: column;
    .main {
        flex: 1;
        display: flex;
        overflow: hidden;
        .code-box {
            height: 100%;
            flex: 1;
            overflow: auto;
        }
        .view-box {
            padding: 10px 20px;
            box-sizing: border-box;
        }
        .combine-box {
            margin-top: 30px;
            height: 694px;
            width: 375px;
            border: 8px solid #000;
            border-radius: 35px;
            overflow: hidden;
        }
    }
}
</style>
